import React, { useState } from 'react'
import NavBar from '@/components/NavBar'
import styles from './index.module.scss'
import { useFormik } from 'formik'
import Input from '@/components/Input'
import * as Yup from 'yup'
import classNames from 'classnames'
import { useDispatch } from 'react-redux'
import { login, sendCode } from '@/store/actions/login'
import { Toast } from 'antd-mobile'
import { useHistory, useLocation } from 'react-router-dom'

export default function Login() {
  const location = useLocation<{ from: string }>()
  const history = useHistory()
  const [time, setTime] = useState(0)
  const dispatch = useDispatch()
  const onExtraClick = async () => {
    if (time > 0) return
    // console.log('点击获取验证码')
    // 先对手机号验证再请求验证码
    if (!/^1[3-9]\d{9}$/.test(mobile)) {
      formik.setTouched({
        mobile: true,
      })
      return
    }

    await dispatch(sendCode(mobile))
    Toast.success('获取验证码成功', 1)

    // 开启倒计时
    setTime(60)
    let timeId = setInterval(() => {
      setTime((time) => {
        if (time === 1) {
          clearInterval(timeId)
        }
        return time - 1
      })
    }, 1000)
  }

  const formik = useFormik({
    initialValues: {
      mobile: '',
      code: '',
    },
    // 表单提交会触发
    onSubmit: async (values) => {
      // console.log(values)
      await dispatch(login(values))
      Toast.success('登录成功！', 1)
      // 登录成功跳转到主页home
      // history.push('/home')
      if (location.state) {
        history.replace(location.state.from)
      } else {
        history.replace('/home')
      }
    },
    // 简单校验
    // validate(values) {
    //   const errors = {}
    //   if (!values.mobile) {
    //     errors.mobile = '手机号不能为空'
    //   }
    //   if (!values.code) {
    //     errors.code = '验证码不能为空'
    //   }
    //   return errors
    // },

    // 用yup校验
    validationSchema: Yup.object({
      mobile: Yup.string()
        .required('手机号不能为空')
        .matches(/^1[3-9]\d{9}$/, '手机号格式不正确'),
      code: Yup.string()
        .required('验证码不能为空')
        .matches(/^\d{6}$/, '验证码格式错误'),
    }),
  })
  const {
    handleBlur,
    handleSubmit,
    handleChange,
    errors,
    touched,
    isValid,

    values: { mobile, code },
  } = formik
  return (
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className="content">
        {/* 标题 */}
        <h3>短信登录</h3>
        <form onSubmit={handleSubmit}>
          {/* 手机号输入框 */}
          <div className="input-item">
            <div className="input-box">
              <Input
                name="mobile"
                autoComplete="off"
                placeholder="请输入手机号"
                value={mobile}
                onChange={handleChange}
                onBlur={handleBlur}
                maxLength={11}
              />
            </div>
            {touched.mobile && errors.mobile ? (
              <div className="validate">{errors.mobile}</div>
            ) : null}
          </div>

          {/* 短信验证码输入框 */}
          <div className="input-item">
            <div className="input-box">
              <Input
                name="code"
                autoComplete="off"
                placeholder="请输入验证码"
                onExtraClick={onExtraClick}
                extra={time === 0 ? '获取验证码' : time + 's后获取'}
                value={code}
                onChange={handleChange}
                onBlur={handleBlur}
                maxLength={6}
              />
              {/* <div className="extra">获取验证码</div> */}
            </div>
            {touched.code && errors.code ? (
              <div className="validate">{errors.code}</div>
            ) : null}
          </div>

          {/* 登录按钮 */}
          <button
            type="submit"
            className={classNames('login-btn', { disabled: !isValid })}
            disabled={!isValid}
          >
            登录
          </button>
        </form>
      </div>
    </div>
  )
}
